package rpg.visual;

import java.awt.Graphics2D;
import java.util.ArrayList;

import pgui.PVisual;
import pgui.visual.PComponent;
import pgui.visual.PImage;
import rpg.visual.menu.VisualMenu;
import square.data.DataGroup;
import square.data.SpriteData;

public class VisualMain extends PComponent {
	public static final int START_WIDTH = 800, START_HEIGHT = 660;

	private VisualMap map;
	private VisualMenu menu;

	public VisualMain(PVisual visual) {
		super(visual);

		// Menu
		menu = new VisualMenu(visual);
		addChild(menu);

		// Map
		map = new VisualMap(visual);
		map.setRelativeX(50);
		map.setRelativeY(50);
		getMap().setX(-getMap().getWidth() / 2);
		getMap().setY((-getMap().getHeight() - 73) / 2);

		PComponent mapBackground = new VisualMapBackground(visual, map);
		addChild(mapBackground);

		addChild(map);
	}

	// Paint Events
	@Override
	public void onPaint(Graphics2D g) {
		Integer lastWidth = this.getLastWidth();
		Integer lastHeight = this.getLastHeight();

		super.onPaint(g);

		boolean resize = false;
		if (lastWidth != null && !lastWidth.equals(this.getLastWidth())) {
			resize = true;
		}

		if (lastHeight != null && !lastHeight.equals(this.getLastHeight())) {
			resize = true;
		}

		if (resize) {
			VisualImage.SQUARE_SIZE = (int) Math.floor((this.getLastHeight() - 128) / VisualMap.DISPLAY_HEIGHT);
			float factor = (float) VisualImage.SQUARE_SIZE
					/ VisualImage.DEFAULT_SQUARE_SIZE;
			
			for (SpriteData it : DataGroup.getSprites()) {
				ArrayList<Object> frames = it.getFrames();
				for (Object frame : frames) {
					((PImage) frame).scale(factor, factor);
				}
			}
			getMap().resize();
			getMap().setX(-getMap().getWidth() / 2);
			getMap().setY((-getMap().getHeight() - 73) / 2);
		}
	}
	
	// Get & Set
	public VisualMap getMap() {
		return map;
	}

	public void setMap(VisualMap visualMap) {
		this.map = visualMap;
	}

	public VisualMenu getMenu() {
		return menu;
	}

	public void setMenu(VisualMenu visualMenu) {
		this.menu = visualMenu;
	}
}
